<template>
    <div class="content-container content-panel">
        <h3 class="main-title">
            <a-row>
                <a-col :span="8" class="left">
                    <a-breadcrumb :routes="routes">
                        <template slot="itemRender" slot-scope="{ route, params, routes, paths }">
                            <span v-if="routes.indexOf(route) === routes.length - 1">
                                <span v-html="route.breadcrumbName"></span>
                            </span>
                            <router-link v-else :to="paths.join('/')">
                                <span v-html="route.breadcrumbName"></span>
                            </router-link>
                        </template>
                    </a-breadcrumb>
                </a-col>
            </a-row>
        </h3>
        <div class="content">
            <div class="query-content">
                <a-form :form="form" hideRequiredMark>
                    <div class="row-container">
                        <a-form-item label="任务编码规则">
                            <a-select
                                v-model="form.codeName"
                                :disabled="detailDisabled"
                                @change="handleChangeRule"
                                placeholder="选择规则"
                            >
                                <a-select-option
                                    v-for="p in codeRuleList"
                                    :key="p.id"
                                    :value="p.name"
                                >{{ p.name }}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="任务编码">
                            <a-input :disabled="!!form.ruleId" v-model="form.code">
                                <a-tooltip slot="suffix" title="规则：xxx-xxx-xxx">
                                    <a-icon type="info-circle" style="color: rgba(0,0,0,.45)" />
                                </a-tooltip>
                            </a-input>
                        </a-form-item>
                        <a-form-item label="物料编码">
                            <a-col span="20">
                                <a-input disabled v-model="form.materialCode" />
                            </a-col>
                            <a-col span="4">
                                <a-button
                                    type="primary"
                                    block
                                    icon="search"
                                    @click="onSearch"
                                    v-show="!detailDisabled"
                                />
                            </a-col>
                        </a-form-item>
                        <a-form-item label="物料名称">
                            <a-input disabled v-model="form.materialName" />
                        </a-form-item>
                        <a-form-item label="批号">
                            <a-input disabled v-model="form.lotNo" />
                        </a-form-item>
                        <a-form-item label="物料类型">
                            <a-input disabled v-model="form.materialType" />
                        </a-form-item>
                        <a-form-item label="取样位置">
                            <a-input v-model="form.samplingSite" />
                        </a-form-item>
                        <a-form-item label="取样料量">
                            <a-input v-model="form.samplingQuantity" suffix="kg" />
                        </a-form-item>
                        <a-form-item label="计划检验时间">
                            <a-date-picker
                                v-model="form.planTimeMoment"
                                @change="onChange"
                                show-time
                                type="date"
                                placeholder="选择日期"
                                style="width: 100%;"
                            />
                        </a-form-item>
                        <a-form-item label="检验类型">
                            <a-select v-model="form.inspectType">
                                <a-select-option
                                    v-for="p in dict.qcTypeOptions"
                                    :key="p.code"
                                    :value="p.value"
                                >{{ p.label }}</a-select-option>
                            </a-select>
                        </a-form-item>

                        <a-form-item label="检验结果">
                            <a-select :disabled="!confirmDisabled" v-model="form.result">
                                <a-select-option
                                    v-for="p in dict.qcResultsOptions"
                                    :key="p.code"
                                    :value="p.value"
                                >{{ p.label }}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="检验标准">
                            <a-select allow-clear v-model="form.inspectStandardId">
                                <a-select-option
                                    v-for="p in qcStandardOptions"
                                    :key="p.code"
                                    :value="p.id"
                                >{{ p.name }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </div>
                </a-form>
            </div>

            <div>
                <span style="color:green;font-weight:bold">检验标准明细：</span>
                <a-button
                    v-show="!detailDisabled"
                    size="small"
                    type="primary"
                    @click="handleOpenModal(record, 'standard')"
                >新增</a-button>
                <a-table
                    size="small"
                    :columns="columns"
                    :dataSource="dataSource"
                    :pagination="false"
                    :rowKey="record => record.materialId"
                    style="clear:right;overflow:auto;margin-top:8px"
                >
                    <!-- 序号 -->
                    <template slot="index" slot-scope="text, record, index">
                        <span>{{ index + 1 }}</span>
                    </template>
                    <template slot="status" slot-scope="text, record">
                        <a-tag
                            v-if="record.status !='0'"
                            :color="dict.status.taskDetail[record.status -1].color"
                        >{{ dict.status.taskDetail[record.status -1].label }}</a-tag>
                    </template>
                    <!-- 操作 -->
                    <template slot="action" slot-scope="text, record, index">
                        <span v-show="!detailDisabled">
                            <span v-show="['2'].includes(record.status)">
                                <a href="javascript:;" @click="handleStartUp(record)">启动</a>
                                <a-divider type="vertical" />
                            </span>
                            <span v-show="['3'].includes(record.status)">
                                <a
                                    href="javascript:;"
                                    @click="handleOpenModal(record, 'entry', index)"
                                >录入</a>
                                <a-divider type="vertical" />
                            </span>
                            <span v-show="['3'].includes(record.status)">
                                <a href="javascript:;" @click="handleDetailSubmit(record)">提交</a>
                                <a-divider type="vertical" />
                            </span>
                            <span v-show="['0','1'].includes(record.status)">
                                <a
                                    href="javascript:;"
                                    @click="handleOpenModal(record, 'standard', index)"
                                >编辑</a>
                                <a-divider type="vertical" />
                            </span>
                            <span v-show="['0','1'].includes(record.status)">
                                <a href="javascript:;" @click="handleDeleteRow(record, index)">删除</a>
                            </span>
                        </span>
                    </template>
                </a-table>
                <a-row :gutter="24" style="margin-top:20px">
                    <a-col :style="{ textAlign: 'center' }">
                        <a-button v-show="confirmDisabled" type="primary" @click="handleConfirm">确认</a-button>
                        <a-button
                            :style="{ marginLeft: '8px' }"
                            v-show="!detailDisabled && !confirmDisabled"
                            type="primary"
                            @click="handleSubmit"
                        >保存</a-button>
                        <a-button :style="{ marginLeft: '8px' }" @click="handleBack">返回</a-button>
                    </a-col>
                </a-row>
            </div>
        </div>
        <!-- 模态框 -->
        <material-query-modal ref="materialQueryModalRef" />
        <employee-query-modal ref="employeeQueryModalRef" />
        <standard-add-edit-modal ref="standardAddEditModalRef" />
        <entry-add-edit-modal ref="entryAddEditModalRef" />
    </div>
</template>

<script>
import "@/assets/query.css";
import moment from "moment";
import dict from "../dict.json";
import Bus from "../../utils/Bus";
import LibsCommonBasics from "libs-common-basics";
import MaterialQueryModal from "../../commons/query/MaterialQueryModal";
import EmployeeQueryModal from "../../commons/query/EmployeeQueryModal";
import StandardAddEditModal from "./components/task/StandardAddEditModal";
import EntryAddEditModal from "./components/task/EntryAddEditModal";
const columns = [
    {
        title: "序号",
        dataIndex: "index",
        width: 90,
        align: "center",
        scopedSlots: { customRender: "index" },
    },
    {
        title: "项目编码",
        dataIndex: "inspectItemCode",
        width: 150,
    },
    {
        title: "项目名称",
        dataIndex: "inspectItemName",
        width: 150,
    },
    {
        title: "标准值",
        dataIndex: "standardValue",
        width: 150,
    },
    {
        title: "最大值",
        dataIndex: "maximumValue",
        width: 150,
    },
    {
        title: "最小值",
        dataIndex: "minimumValue",
        width: 150,
    },
    {
        title: "单位",
        dataIndex: "measureUnit",
        width: 150,
    },
    {
        title: "是否数值",
        dataIndex: "dataTypeName",
        width: 150,
    },
    {
        title: "检验值",
        dataIndex: "inspectValue",
        width: 150,
    },
    {
        title: "检验结果",
        dataIndex: "resultName",
        width: 150,
    },
    {
        title: "检验记录",
        dataIndex: "records",
        width: 150,
    },
    {
        title: "状态",
        dataIndex: "status",
        width: 150,
        scopedSlots: { customRender: "status" },
    },
    {
        title: "检验人",
        dataIndex: "inspectorName",
        width: 150,
    },
    {
        title: "检验时间",
        dataIndex: "inspectorTime",
        width: 150,
    },
    {
        title: "操作",
        key: "action",
        width: 400,
        scopedSlots: { customRender: "action" },
    },
];

const routes = [
    {
        path: "../../main/qc-task",
        breadcrumbName: "检验任务",
    },
    {
        path: "./taskDetail",
        breadcrumbName: "",
    },
];

export default {
    components: { EmployeeQueryModal, MaterialQueryModal, StandardAddEditModal, EntryAddEditModal },
    data() {
        return {
            dict,
            routes,
            form: {},
            columns,
            dataSource: [],
            index: -1, // 点击编辑使用
            detailDisabled: false, // 详情禁用
            confirmDisabled: false, // 确认禁用
            codeRuleList: [],
            qcStandardOptions: [],
            queryParams: {
                data: {},
                pageNum: parseInt(LibsCommonBasics.LibsPagination.props.pageNum.default),
                pageSize: parseInt(LibsCommonBasics.LibsPagination.props.pageSize.default),
            },
        };
    },
    methods: {
        moment,
        // 打开子窗口
        handleOpenModal(record, flag, index) {
            let self = this;
            if (!record) {
                self.index = -1;
            } else {
                self.index = index;
                record.code = record.inspectItemCode;
                record.name = record.inspectItemName;
            }
            this.$refs[flag + "AddEditModalRef"].openModal(record);
        },
        // 搜索
        onSearch() {
            this.$refs.materialQueryModalRef.openModal();
        },
        // 选取时间
        onChange(date, dateString) {
            // debugger;
            if (date) {
                this.form.planTime = dateString;
                this.form.planTimeMoment = date;
                this.$forceUpdate();
            }
        },
        // 删除行
        handleDeleteRow(record, index) {
            this.dataSource = this.dataSource.filter((item, i) => {
                return i != index;
            });
        },
        // 启动
        handleStartUp(record) {
            // debugger;
            let self = this;
            let params = {
                id: record.id,
            };
            self.$store
                .dispatch(dict.action.task.startDetailAction, params)
                .then(res => {
                    if (parseInt(res.code) === 1) {
                        self.$message.success("成功");
                        self.initDetail();
                    } else {
                        self.$message.error("失败" + res.msg + "(" + res.code + ")");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },

        // 详情确认
        handleConfirm() {
            let self = this;
            let params = {
                id: self.form.id,
                result: self.form.result,
                samplingQuantity: self.form.samplingQuantity,
            };
            self.$store
                .dispatch(dict.action.task.confirmAction, params)
                .then(res => {
                    if (parseInt(res.code) === 1) {
                        // debugger
                        self.$message.success("成功");
                        self.handleBack();
                        self.$parent.init();
                    } else {
                        self.$message.error("失败" + res.msg + "(" + res.code + ")");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 详情提交
        handleDetailSubmit(record) {
            let self = this;
            let params = {
                id: record.id,
            };
            self.$store
                .dispatch(dict.action.task.submitDetailAction, params)
                .then(res => {
                    if (parseInt(res.code) === 1) {
                        self.$message.success("成功");
                        self.initDetail();
                    } else {
                        self.$message.error("失败" + res.msg + "(" + res.code + ")");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 确定提交表单
        handleSubmit() {
            let self = this;
            self.form.details = self.dataSource;
            self.$store
                .dispatch(self.action, self.form)
                .then(res => {
                    if (parseInt(res.code) === 1) {
                        self.$message.success("成功");
                        self.handleBack();
                        self.$parent.init();
                    } else {
                        self.$message.error("失败" + res.msg + "(" + res.code + ")");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 后退
        handleBack() {
            this.$router.go(-1);
        },

        
        initStandard() {
            let self = this;
            let params = {
                standardName: "",
                materialId: self.form.materialId,
            };
            this.$store
                .dispatch(dict.action.common.standardQueryAction, params)
                .then(res => {
                    if (parseInt(res.code) === 1) {
                        // debugger;
                        self.qcStandardOptions = res.data;
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 初始化详情
        initDetail() {
            let self = this;
            let params = {
                id: self.form.id,
            };
            this.$store
                .dispatch(dict.action.task.viewAction, params)
                .then(res => {
                    if (parseInt(res.code) === 1) {
                        // debugger;
                        // this.form = data;
                        this.dataSource = res.data.details;
                        // this.form.planTimeMoment = moment(this.form.planTime);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 编码规则选择
        handleChangeRule(value, option) {
            // debugger;
            let _obj = this.codeRuleList.filter(item => item.name === value)[0];
            this.form.ruleId = _obj.id;
            // this.form.codeName = _obj.name;
            this.form.codeDescription = _obj.description;
        },
        initCodeRule() {
            let self = this;
            let params = {
                type: "",
            };
            this.$store
                .dispatch(dict.action.common.codeRuleQueryAction, params)
                .then(res => {
                    if (parseInt(res.code) === 1) {
                        // debugger;
                        let _item = {
                            id: "",
                            name: "自定义",
                            description: "自定义规则",
                        };
                        self.codeRuleList = [...res.data, _item];
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 初始化
        init() {
            this.initCodeRule();
            this.initStandard();
        },
    },
    mounted() {
        // debugger
        let self = this;
        let flag = this.$route.query.flag;
        let data = this.$route.query.data;
        switch (flag) {
            case "add":
                routes[1].breadcrumbName = "新增检验任务";
                this.action = dict.action.task.addAction;
                break;
            case "edit":
                routes[1].breadcrumbName = "编辑检验任务";
                this.action = dict.action.task.editAction;
                this.form = data;
                this.dataSource = data.details;
                this.form.planTimeMoment = moment(this.form.planTime);
                break;
            case "confirm":
                routes[1].breadcrumbName = "确认检验任务";
                this.action = dict.action.task.confirmAction;
                this.form = data;
                this.dataSource = data.details;
                this.form.planTimeMoment = moment(this.form.planTime);
                this.confirmDisabled = true;
                break;
            case "detail":
                routes[1].breadcrumbName = "检验任务详情";
                this.action = dict.action.task.editAction;
                this.form = data;
                this.dataSource = data.details;
                this.form.planTimeMoment = moment(this.form.planTime);
                this.detailDisabled = true;
                break;
        }
        Bus.$on("standard", function (item) {
            // debugger;
            item.inspectItemCode = item.code;
            item.inspectItemName = item.name;
            if (self.index === -1) {
                item.status = "0";
                self.dataSource.push(item);
            } else {
                self.dataSource[self.indexindex] = item;
            }
        });
        Bus.$on("entry", function (item) {
            // debugger;
            self.dataSource[self.index].inspectValue = item.inspectValue;
            self.dataSource[self.index].result = item.result;
            self.dataSource[self.index].resultName = dict.qcDetailResultsOptions[item.result].label;
        });
        Bus.$on("material", function (item) {
            // debugger;
            self.form.materialId = item.materialId;
            self.form.materialCode = item.materialCode;
            self.form.materialName = item.materialName;
            self.form.lotNo = item.materialLot;
            self.form.materialType = item.materialType.materialTypeName;
            self.$forceUpdate();
        });
        self.init();
    },
};
</script>
